<template>
  <view class="page container">
    <u-form
      :model="basicForm"
      :rules="rules"
      labelPosition="top"
      ref="form"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <u-form-item label="款项名称" prop="paymentName" required>
          <h-select-checkoutlist-input-popup
            v-model="basicForm.paymentName"
            objectField="basicForm.paymentName"
            :contractId="contractId"
            placeholder="请选择款项名称"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @detail="getCheckoutInfo"
            @onErr="getCheckoutInfoErr"
          ></h-select-checkoutlist-input-popup>
        </u-form-item>
        <u-form-item label="应收金额（元）" prop="amountReceivable" :borderBottom="false" required>
          <h-money-input placeholder="请输入金额" v-model="basicForm.amountReceivable"></h-money-input>
        </u-form-item>
        <u-form-item label="豁免类型" prop="exemptionType" required>
          <h-select-input-tag
            style="width: 100%"
            v-model="basicForm.exemptionType"
            objectField="basicForm.exemptionType"
            placeholder="请选择类型"
            border="surround"
            :dictName="'exemption_type'"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="lxChange"
          ></h-select-input-tag>
        </u-form-item>
        <template v-if="basicForm.exemptionType === '1'">
          <u-form-item label="豁免对象" prop="exemptionManagementTeam">
            <h-select-team-input-popup
              disabled
              style="width: 100%"
              v-model="basicForm.exemptionManagementTeam"
              objectField="basicForm.exemptionManagementTeam"
              placeholder="请选择豁免对象"
              border="surround"
              :tdlx="1"
            />
          </u-form-item>
        </template>
        <template v-if="basicForm.exemptionType === '2'">
          <u-form-item label="豁免对象" prop="exemptionUndertaker">
            <h-select-person-input-popup
              style="width: 100%"
              disabled
              v-model="basicForm.exemptionUndertaker"
              placeholder="请选择豁免对象"
              border="surround"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
              objectField="basicForm.exemptionUndertaker"
            ></h-select-person-input-popup>
          </u-form-item>
        </template>
        <template v-if="basicForm.exemptionType === '3'">
          <u-form-item label="豁免对象" prop="exemptionProjectHead">
            <!-- <u--input
              v-model="basicForm.exemptionProjectHead"
              placeholder="请输入豁免对象"
              border="surround"
              :fontSize="12"
              disabled
            ></u--input> -->
            <h-select-exemption-objects-input-popup
              :dictOptions="dictOptions"
              :muitFlag="true"
              :projectId="projectId"
              v-model="basicForm.exemptionProjectHead"
              style="width: 100%"
              placeholder="请选择豁免对象"
              searchPlaceholder="请选择"
              border="surround"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
              @select="exemptionObjectsInputSelect"
            ></h-select-exemption-objects-input-popup>
          </u-form-item>
        </template>
        <u-form-item label="豁免考核起始月份" prop="exemptionDateBegin" required>
          <h-time-select
            v-model="basicForm.exemptionDateBegin"
            placeholder="请选择起始月份"
            border="surround"
            :mode="'year-month'"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="handleBeginDateChange"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="豁免考核结束月份" prop="exemptionDateEnd" required>
          <h-time-select
            v-model="basicForm.exemptionDateEnd"
            placeholder="请选择结束月份"
            border="surround"
            :mode="'year-month'"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="handleEndDateChange"
						:minDate="basicForm.exemptionDateBegin?(new Date(basicForm.exemptionDateBegin)).getTime():315504000000"
						:maxDate="maxDate"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="豁免罚款金额（元）" prop="exemptionPenaltyAmount" required>
          <h-money-input placeholder="请输入豁免罚款金额" v-model="basicForm.exemptionPenaltyAmount"></h-money-input>
        </u-form-item>
      </view>

      <view class="space-x-1 mt-1" style="display: flex">
        <u-button type="primary" text="关闭" :plain="true" :loading="loading" @click="onClose"></u-button>
        <u-button type="primary" text="保存" :loading="loading" @tap="$u.debounce(onSubmit, 500)"></u-button>
      </view>
      <u-toast ref="uToast"></u-toast>
    </u-form>
  </view>
</template>

<script>
import moment from 'moment'

export default {
  name: 'PaybackDisclaimerForm',
  props: {
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    index: {
      type: Number,
      default: null,
    },
    projectId: {
      type: String,
      default: '',
      required: false,
    },
    contractId: {
      type: String,
      default: '',
      required: false,
    },
    managementTeam: {
      type: String,
      default: '',
      required: false,
    },
    undertaker: {
      type: String,
      default: '',
      required: false,
    },
    projectLeadingToSubTableText: {
      type: String,
      default: '',
      required: false,
    },
    projectLeadingToSubTable: {
      type: String,
      default: '',
      required: false,
    },
    dictOptions: {
      type: Object,
      default: () => {},
      required: false,
    },
  },
  data() {
    return {
      smallList: [],
      loading: false,
      basicForm: {
        paymentName: '',
        amountReceivable: '',
        exemptionType: '',
        exemptionManagementTeam: '',
        exemptionUndertaker: '',
        exemptionProjectHead: '',
        // exemptionProjectHeadId: '',
        exemptionDateBegin: '',
        exemptionDateEnd: '',
        exemptionPenaltyAmount: '',
      },
      rules: {
        paymentName: [{ required: true, message: '请选择款项名称!', trigger: ['blur', 'change'] }],
        amountReceivable: [
          {
            required: true,
            pattern: /^(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
            message: '请输入应收金额!',
            trigger: ['blur', 'change'],
          },
        ],
        exemptionType: [{ required: true, message: '请选择豁免类型!', trigger: ['blur', 'change'] }],
        exemptionDateBegin: [{ required: true, message: '请选择豁免考核起始月份!', trigger: ['blur', 'change'] }],
        exemptionDateEnd: [{ required: true, message: '请选择豁免考核结束月份!', trigger: ['blur', 'change'] }],
        exemptionPenaltyAmount: [{ required: true, message: '请输入豁免罚款金额!', trigger: ['blur', 'change'] }],
      },
      modelNew: {},
    }
  },
	computed: {
		maxDate () {
			var mom = ''
			if (!this.basicForm.exemptionDateBegin) {
				mom = moment().add(2, 'months').format('x')
				return 
			} else {
				mom = moment(this.basicForm.exemptionDateBegin).add(2, 'months').format('x')
				return Number(mom)
			}
			
		}
	},
  methods: {
    exemptionObjectsInputSelect(obj) {
      if (obj) {
        // this.$set(this.basicForm, 'exemptionProjectHead', obj.data)
        // this.$set(this.basicForm, 'exemptionProjectHeadId', obj.id)
        this.$set(this.basicForm, 'exemptionProjectHead', obj.id)
      }
    },
    handleBeginDateChange(date, dateStr) {
      this.$set(this.basicForm, 'exemptionDateEnd', undefined)
      // this.predictReturnDate = undefined
    },
    handleEndDateChange(date, dateStr) {
      if (!this.basicForm.exemptionDateBegin) {
        return false
      }
      let isBefore = moment(this.basicForm.exemptionDateBegin).isBefore(this.basicForm.exemptionDateEnd)
      if (!isBefore) {
        const format = 'YYYY-MM-DD'
        const exemptionDateBegin = moment(this.basicForm.exemptionDateBegin, format)
        const exemptionDateEnd = moment(this.basicForm.exemptionDateEnd, format)
        if (exemptionDateBegin.isSame(exemptionDateEnd)) {
          return false
        }
        this.$u.toast('结束日期必须大于起始日期！')
        this.$nextTick(() => {
          this.basicForm.exemptionDateEnd = null
        })
      }
    },
    lxChange(value) {
      if (value) {
        if (value === '1') {
          this.$nextTick(() => {
            this.$set(this.basicForm, 'exemptionManagementTeam', this.managementTeam)

            //清空其他数据
            this.$set(this.basicForm, 'exemptionUndertaker', null)
            this.$set(this.basicForm, 'exemptionProjectHead', null)
            // this.$set(this.basicForm, 'exemptionProjectHeadId', null)
          })
        }
        if (value === '2') {
          this.$nextTick(() => {
            this.$set(this.basicForm, 'exemptionUndertaker', this.undertaker)

            //清空其他数据
            this.$set(this.basicForm, 'exemptionManagementTeam', null)
            this.$set(this.basicForm, 'exemptionProjectHead', null)
            // this.$set(this.basicForm, 'exemptionProjectHeadId', null)
          })
        }
        if (value === '3') {
          this.$nextTick(() => {
            // this.$set(this.basicForm, 'exemptionProjectHead', this.projectLeadingToSubTableText)
            // this.$set(this.basicForm, 'exemptionProjectHeadId', this.projectLeadingToSubTable)

            //清空其他数据
            this.$set(this.basicForm, 'exemptionManagementTeam', null)
            this.$set(this.basicForm, 'exemptionUndertaker', null)
          })
        }
      }
    },
    // 合同款项详情
    getCheckoutInfo(data) {
      if (data) {
        this.$set(this.basicForm, 'contractMoneyItemId_dictText', data.nodeName)
        this.$set(this.basicForm, 'receivables', data.paymentMoney)
        this.$set(this.basicForm, 'collectedMoney', data.realCollectionPaymentMoney)
        this.$set(this.basicForm, 'totalDeductMoney', data.deductMoney)

        if (this.clickManagerTrusteePopup == 'edit') {
          if (this.isCheckoutInfoRefresh) {
            this.$set(this.basicForm, 'amount', '')
            this.$set(this.basicForm, 'deductMoney', '')
            this.$set(this.basicForm, 'unreturnedMoney', '')
          } else {
            this.isCheckoutInfoRefresh = true
          }
        } else {
          this.$set(this.basicForm, 'amount', '')
          this.$set(this.basicForm, 'deductMoney', '')
          this.$set(this.basicForm, 'unreturnedMoney', '')
        }
      }
    },

    // 获取合同款项报错
    getCheckoutInfoErr() {
      uni.showToast({
        title: '请先选择合同',
        icon: 'none',
      })
    },

    reset() {
      this.$refs.form.resetFields()
    },
    async onSubmit() {
      await this.$refs.form.validate()
      if (!this.index) {
        this.$emit('submit', [
          {
            id: parseInt(Math.random() * 1000000000000),
            ...this.basicForm,
          },
          this.index,
        ])
      } else {
        this.$emit('submit', [this.basicForm, this.index])
      }
      // this.reset()
    },
    onClose() {
      this.$emit('close')
      this.reset()
    },
  }
}
</script>

<style scoped>
/* .page.container {
  padding: 20px;
}
.basic-style {
  margin: 0;
  height: 500px;
}
.u-form-item {
  padding: 0px 8px;
} */
</style>
